<?php
namespace app\admin\model;

use think\Model;
use app\common\util\DBUtil;

/**
 * 后台菜单模型
 * @package app\admin\model
 */
class AuthRule extends Model
{
    protected $not_check_id=[1];//不检测权限的管理员id
    protected $not_check_url=['admin/index/index','admin/Sys/clear'];//不检测权限的url

    /**
     * 获取所有父节点id(含自身)
     * @param int $id 节点id
     * @return array
     */
    // public function get_admin_parents($id =0)
    // {
    //     $id=$id?:$this->get_url_id('',1);
    //     if(empty($id)) return [];
    //     $lists=self::order('level desc,sort')->column('pid','id');
    //     $ids = [];
    //     while (isset($lists[$id]) && $lists[$id] !=0){
    //         $ids[]=$id;
    //         $id=$lists[$id];
    //     }
    //     if(isset($lists[$id]) && $lists[$id]==0) $ids[]=$id;
    //     return array_reverse($ids);
    // }
    /**
     * 获取当前节点及父节点下菜单(仅显示状态)
     * @param int $id 节点id
     * @return array|mixed
     */
    // public function get_admin_parent_menus(&$id)
    // {
    //     $id=$this->get_url_id('',1);
    //     $pid=self::where('id',$id)->value('pid');
	// 	//取$pid下子菜单
	// 	$menus=self::where(array('status'=>1,'pid'=>$pid))->order('sort')->select();
    //     return $menus;
    // }
    /**
     * 获取不需要验证的节点id
     * @return array
     */
    // public static function get_notcheck_ids()
    // {
    //     $ids = self::where('notcheck', 1)->column('id');
    //     return $ids;
    // }
    /**
     * 获取指定url的id(可能为显示状态或非显示状态)
     * @param string $url 为空获取当前操作的id
     * @param int $status 1表示取显示状态,为空或为0则不限制
     * @return int -1表示不需要检测 0表示无后台菜单 其他表示当前url对应id
     */
    // public function get_url_id($url='',$status=0)
    // {
    //     $url=$url?:request()->module().'/'.request()->controller().'/'.request()->action();
    //     if($url=='//'){
    //         $routeInfo=request()->routeInfo();
    //         //插件管理
    //         if($routeInfo['route']=='\think\addons\Base@execute'){
    //             // $menu_id = self::where('name','admin/Addons/addons_list')->order('level desc,sort')->value('id');
    //             return $menu_id?:0;
    //         }
    //     }
    //     if(in_array($url,$this->not_check_url)) return -1;
    //     if(in_array($url,['admin/Model/cmslist','admin/Model/cmsadd'])){
    //         $id=get_query();
    //         if(isset($id['id'])){
    //             $id=$id['id'];
    //             $url.='?id='.$id;
    //         }
    //     }
	// 	$where['name']=$url;
	// 	if($status) $where['status']=$status;
    //     $menu_id = self::where($where)->order('level desc,sort')->value('id');//4级或3级(如果4级,status是0,不显示)
    //     $menu_id=$menu_id?:0;
    //     return $menu_id;
    // }

    

    public function get_url($url=''){
        return $url?:request()->module().'/'.request()->controller().'/'.request()->action();       
    }

    public function get_url_info($url){
        $adminMenu = config("admin_menu");        
        return 1;
    }
    

    public function check_url_auth($url) {
        // 1如果是不需需要检查的URL,也不需要检查
        if(in_array($url, $not_check_url)) {
            return true;
        }
        // 1如果是超级管理员 admin， 不需要检查
        $uid = session('admin_auth.aid');
        if(in_array($uid, $not_check_id)){
            return true;
        }
    
        

    }
    

    public function check_auth($url, $id){
        $url=$url?:request()->module().'/'.request()->controller().'/'.request()->action();        
        $url = strtolower($url);

        
        if(in_array($url, $this->not_check_url)) {
            return true;
        }

        if($id < 0){

            return false;
        }
        $groupid = session('user.groupid');
        if($groupid == 1){
            return true;
        }
        $uid = session('uid');
        $auth_ids_list = $this->get_auth_list($uid);

        if(empty($auth_ids_list)) {
            var_dump($auth_ids_list);
            return false;
        }
        $id=$id?:$this->get_url_id($url);
        if(in_array($id,$auth_ids_list)){
            return true;
        }else{
            
            return false;
        }
    }
    /**
     * 权限检测
     * @param int
     * @return boolean
     */
    public function checkAuth($id=0)  {

        // 1如果是无需检查的页面
        $id=$id?:$this->get_url_id();
        if($id==-1) return false;

        $uid=session('admin_auth.aid');
        if(in_array($uid,$this->not_check_id)) return true;
        $auth_ids_list=cache('auth_ids_list_'.$uid);
        if(empty($auth_ids_list)){
            $auth_ids_list = $this->get_auth_list($uid);
            cache('auth_ids_list_'.$uid,$auth_ids_list);
        }

        if(empty($auth_ids_list)) return false;
        if(in_array($id,$auth_ids_list)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 菜单检查是否有效
     * @param int
     * @return string 返回''表示无效,否则返回正确的name字符串
     */
    public static function check_name($name,$level=1)
    {
        $module='admin';
        $arr=explode('/',$name);
        $count=count($arr);
        $rst='';
        if($level==1){
            if($count>1){
                $module=strtolower($arr[0]);
                $controller=ucfirst($arr[1]);
            }else{
                $controller=ucfirst($name);
            }
            if (has_controller($module,$controller)) {
                $rst=$module.'/'.$controller;
            }
        }elseif($level==2){
            $rst=$name;
        }else{
            if($count>2){
                $module=strtolower($arr[0]);
                $controller=ucfirst($arr[1]);
                $action=$arr[2];
            }elseif($count==2){
                $controller=ucfirst($arr[0]);
                $action=$arr[1];
            }else{
                return $rst;
            }
            if($action){
                //判断$action是否含?
                $arr=explode('?',$action);
                $_action=(count($arr)==1)?$action:$arr[0];
                if(has_action($module,$controller,$_action)==2){
                    $rst=$module.'/'.$controller.'/'.$action;
                }
            }
        }
        return $rst;
    }

    // /**
    //  * 获取权限菜单
    //  * @return array
    //  */
    // public function get_admin_menus($allMenus){
    //     $uid = session('uid');
    //     $groupId = session("user")['groupid'];

    //     $db = DBUtil::connect_admin();
    //     if($groupId == 0) {
    //         return $allMenus;
    //     }
    //     $group = $this->get_group_menu($groupId);      
       
    // }

    public static function validGroupMenu($allMenus, $groupMenus) {
        if(!$groupMenus) {
            return array();
        }
        $menus = array();
        foreach($allMenus as $menuId => $menu) {
            $childMenu = $menu['_child'];
            foreach($childMenu as $childId => $child) {
                if(!in_array($childId, $groupMenus)) {
                    if(!$menus[$menuId]) $menus[$menud] = array();
                    $menus[$menud][$childId] = $child;
                }
            }
        }
        return $menus;
    }

    public function get_group_menu($groupId) {
        $db = DBUtil::connect_admin();
        $group = $db->table('admin_user_group')->where("groupid", $groupId)->find();               
        return $this::preprocess_admin_group($group);
    }

    public static function preprocess_admin_group($group){
        $group['menus'] = $group['rules'] ?: explode(",", $group('rules'));
        return $group;
    }

    
    public function get_admin_menus2()
    {
        $uid=session('admin_auth.aid');
        $menus=cache('menus_admin_'.$uid);
        if($menus) return $menus;
        $where['status']=1;
        if(!in_array($uid,$this->not_check_id)){
            $auth_ids_list=cache('auth_ids_list_'.$uid);
            if(empty($auth_ids_list)){
                $auth = new Auth();
                $auth_ids_list=$auth->get_auth_list($uid,1,'id');
                cache('auth_ids_list_'.$uid,$auth_ids_list);
            }
            if(empty($auth_ids_list)) return [];
            $where['id']=array('in',$auth_ids_list);
        }
        $data = self::where($where)->order('sort')->select();
        $tree=new \Tree();
        $tree->init($data,['child'=>'_child','parentid'=>'pid']);
        $menus=$tree->get_arraylist($data);
        cache('menus_admin_'.$uid,$menus);
        return $menus;
    }
    /**
     * 获取权限菜单
     * @return array
     */
    public static function get_rules_tree() {
        $data=self::order('sort')->select();
        $data=collection($data)->toArray();
        $tree=new \Tree();
        $tree->init($data,['child'=>'sub','parentid'=>'pid']);
        $rst=$tree->get_arraylist($data);
        return $rst;
    }



 public function check($name, $uid) {
        $authList = $this->get_auth_list($uid);
        $menuId = $this->get_url_id($name);

        if($menuId <= 0){
            return false;
        }
        return in_array($menuId, $authList);        
    }


    public function get_url_menu_ids($url){
        $url=$url?:request()->module().'/'.request()->controller().'/'.request()->action();
        $url = strtolower($url);
        $centerMenuList = config('admin_menu.center');
        $gameMenuList = config('admin_menu.center');

        foreach($centerMenuList as $key => $value) {
           foreach($value['_child'] as $kk => $vv) {
             if($vv['name'] == $url) {
                    return array($key, $kk);
                  // return $kk;
              }                 
          }
        }
        
        foreach ($gameMenuList as $key => $value) {
            foreach($value['_child'] as $kk => $vv) {
                if($vv['name'] == $url) {
                    return array($key, $kk);
                   // return $kk;
                }                 
            }
        }
        // var_dump($url)
        return array(0, -1);
    }
    
    
    public function get_url_id($url='') {
        $url=$url?:request()->module().'/'.request()->controller().'/'.request()->action();
        $url = strtolower($url);
        $centerMenuList = config('admin_menu.center');
        $gameMenuList = config('admin_menu.center');

        foreach($centerMenuList as $key => $value) {
           foreach($value['_child'] as $kk => $vv) {
             if($vv['name'] == $url) {
                  return $kk;
              }                 
          }
        }
        
        foreach ($gameMenuList as $key => $value) {
            foreach($value['_child'] as $kk => $vv) {
                if($vv['name'] == $url) {
                   return $kk;
                }                 
            }
        }
        // var_dump($url)
        return -1;
    }
    
    // 获取用户组的权限列表
    public function get_auth_list($uid) {

        // 可以实时，也可以通过缓存，控制缓存时间        
        
        $sql = "SELECT b.rules FROM admin_user a, admin_group b, admin_group_platform c WHERE a.groupid=b.groupid AND b.groupid=c.groupid AND a.id=? AND c.platform=?";
        $db = DBUtil::connect_admin();
        $ruleList = $db->query($sql,[$uid, config('platform')]);
        $menuIds = array();
        foreach($ruleList as $rule) {
            $menuIds = array_merge($menuIds, explode(",", trim($rule['rules'])));
        };
        $menuIds = array_unique($menuIds);
        if(empty($menuIds)) {
            return array();
        }   

        return $menuIds;
    }

    public function get_auth_list_by_group($groupid){
        $sql = "SELECT b.rules FROM admin_group b, admin_group_platform c WHERE  b.groupid=c.groupid AND b.groupid=? AND c.platform=?";
        $db = DBUtil::connect_admin();
        $ruleList = $db->query($sql,[$groupid, config('platform')]);


        $menuIds = array();
        foreach($ruleList as $rule) {
            $menuIds = array_merge($menuIds, explode(",", trim($rule['rules'])));
        };
        $menuIds = array_unique($menuIds);
        
        if(empty($menuIds)) {
            return array();
        }   

        return $menuIds;
    }


   

    public function getMenuList($groupid, $allMenu) {
        if($groupid == 1){   
            
            $newMenuList = $allMenu;
            foreach($newMenuList as $menuId => $menu) {
                $subMenu = $menu['_child'];               
                $newSubMenu = $subMenu;
                foreach($subMenu as $submenuId => $menuValue) {                
                    if(!($menuValue['is_hide'] == 0)) {                    
                        unset($newSubMenu[$submenuId]);
                    }
                }
                if(count($newSubMenu) == 0) {
                    unset($newMenuList[$menuId]);
                } else {
                    $newMenuList[$menuId]['_child'] = $newSubMenu;
                }
            }
            return $newMenuList;
        }
                
        $authList = $this->get_auth_list_by_group($groupid);
        $newMenuList = $allMenu;        
        foreach($newMenuList as $menuId => $menu) {
            $subMenu = $menu['_child'];
            $newSubMenu = $subMenu;
            foreach($subMenu as $submenuId => $menuValue) {                
                if(!($menuValue['is_hide'] == 0 && in_array($submenuId, $authList))) {                    
                    unset($newSubMenu[$submenuId]);
                }
            }
            if(count($newSubMenu) == 0) {
                unset($newMenuList[$menuId]);
            }else {

                $newMenuList[$menuId]['_child'] = $newSubMenu;
            }
        }

        return $newMenuList;
        
    }

}
